package com.profgj.profgj.controller;

import com.profgj.profgj.entity.Product;
import com.profgj.profgj.entity.ProductMonthEnergyconsumption;
import com.profgj.profgj.entity.ProductYearEnergyconsumption;
import com.profgj.profgj.enums.CalculatedValue;
import com.profgj.profgj.enums.ServerStatus;
import com.profgj.profgj.service.*;
import com.profgj.profgj.utils.EmptyUtils;
import com.profgj.profgj.utils.ReturnOperator;
import com.profgj.profgj.validater.ProductMonthEnergyconsumptionVoValidator;
import com.profgj.profgj.vo.*;
import io.swagger.annotations.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * (产品月能耗)控制层
 * 包括产品月能耗+企业名+ 项目名 + 产品名 的显示
 * 产品月能耗的增删改操作
 *
 * @author 杨帅
 * @since 2021-06-22 11:09:35
 */

/**
 * JSON格式返回
 */
@RestController
/**
 * 请求基路径
 */
@RequestMapping("/eny")
@Api(tags = {"产品月能耗"},description = "产品月能耗")
public class ProductMonthEnergyController {


    /**
     * 产品月能耗服务对象
     */
    @Resource
    private ProductMonthEnergyconsumptionService productMonthEnergyconsumptionService;

    /**
     * 产品年能耗计算服务对象
     */
    @Resource
    private ProductYearEnergyconsumptionService productYearEnergyconsumptionService;


    /**
     * 项目的总能耗计算服务对象
     */
    @Resource
    private ProjectTotalEnergyconsumptionService projectTotalEnergyconsumptionService;

    /**
     * 产品服务对象
     */
    @Resource
    private ProductService productService;

    /**
     * 项目基本信息服务对象
     */
    @Resource
    private ProjectBaseInfoService projectBaseInfoService;


    /**
     * 返回空对象的替代品
     */
    private EmptyObject emptyObject = new EmptyObject();
    
    /**
     * 初始化设置校验器
     * @param binder    校验器绑定对象
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {

        binder.setValidator(new ProductMonthEnergyconsumptionVoValidator());
    }

    /**
     * 产品月能耗id查询
     * @param id    产品月能耗id
     * @param session   Http回话对象内部存储当前登录的用户  user_id / user_name / role_id
     * @return
     */
    @GetMapping("/energy/{id}")
    @ApiOperation(value = "产品月能耗id查询",produces = "application/json",consumes = "application/json")
    @ApiImplicitParam(name = "id",value = "产品月能耗id",dataType = "Long", paramType = "Long", required = true)
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> productMonthEnergyQueryByIdMethod(@PathVariable("id")Long id, @ApiIgnore HttpSession session){

        // 参数校验
        if(!EmptyUtils.isLongEmpty(id)){
            return ReturnOperator.createResultMsg("", ServerStatus.ID_NOT_NULL, ServerStatus.ERROR,
                    new ArrayList<>(), emptyObject, HttpStatus.OK);
        }

        // 取得当前登录的用户角色id
        Integer role_id = Integer.valueOf(String.valueOf(session.getAttribute("role_id")));
        // 取得当前登录的用户id
        Integer user_id = Integer.valueOf(String.valueOf(session.getAttribute("user_id")));

        // 包含产品月能耗和 项目名称 和 产品名称对象
        ProductMonthEnergyconsumptionVo productMonthEnergyconsumptionVo = null;
        // 不是管理员的情况下
        if (role_id != 1) {
            // 通过产品月能耗id和关联企业用户id查询
            productMonthEnergyconsumptionVo = productMonthEnergyconsumptionService.queryProductMonthEnergyByIdAndUserId(id, user_id);
        }else {
            // 管理员情况下查询 产品月能耗id查询
            productMonthEnergyconsumptionVo = productMonthEnergyconsumptionService.queryProductMonthEnergyById(id);
        }

        // 查询结果参数校验
        if (!EmptyUtils.isProductMonthEnergyconsumptionEmpty(productMonthEnergyconsumptionVo)) {
            return ReturnOperator.createResultMsg("", ServerStatus.QUERY_MESSAGE_ERR, ServerStatus.ERROR,
                    new ArrayList<>(), emptyObject, HttpStatus.OK);
        }

        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.QUERY_MESSAGE_SUCCESS, "", ServerStatus.OK,
                new ArrayList<>(), productMonthEnergyconsumptionVo, HttpStatus.OK);
    }


    /**
     * 产品id和年份查询产品月能耗list
     * @param productId 产品id
     * @param year      年份
     * @return
     */
    @GetMapping("/energy/year/{productId}/{year}")
    @ApiOperation(value = "产品id和年份查询产品月能耗list",produces = "application/json",consumes = "application/json")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "productId",value = "产品id",dataType = "Long", paramType = "Long", required = true),
        @ApiImplicitParam(name = "year",value = "年份",dataType = "Integer", paramType = "Integer", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> productMonthEnergyQueryByProductIdAndYearMethod(@PathVariable("productId")Long productId,@PathVariable("year") Integer year){

        if(!EmptyUtils.isLongEmpty(productId)){
            return ReturnOperator.createResultMsg("", ServerStatus.ID_NOT_NULL, ServerStatus.ERROR,
                    new ArrayList<>(), emptyObject, HttpStatus.OK);
        }
        if (!EmptyUtils.isIntegerEmpty(year)) {
            return ReturnOperator.createResultMsg("", ServerStatus.YEAR_NOT_NULL, ServerStatus.ERROR,
                    new ArrayList<>(), emptyObject, HttpStatus.OK);
        }

        // 产品id和年查询 产品该年的所有月能耗
        List<ProductMonthEnergyconsumptionVo> pMEV = productMonthEnergyconsumptionService.queryProductMonthEnergyAndProductByIdAndYear(productId,year);

        // 查询结果校验
        if(!EmptyUtils.isProductMonthEnergyconsumptionListEmpty(pMEV)){
            return ReturnOperator.createResultMsg("", ServerStatus.QUERY_MESSAGE_ERR, ServerStatus.ERROR,
                    new ArrayList<>(), emptyObject, HttpStatus.OK);
        }

        // 返回查询结果
        return ReturnOperator.createResultMsg(ServerStatus.QUERY_MESSAGE_SUCCESS, "", ServerStatus.OK,
                pMEV, emptyObject, HttpStatus.OK);
    }


    /**
     * 关键字分页查询产品月能耗
     * @param draw    绘制次数
     * @param start    查询起始位置
     * @param length     查询条数
     * @param search  产品能耗关键字
     * @param session   Http回话对象内部存储当前登录的用户  user_id / user_name / role_id
     * @return
     */
    @GetMapping("/energy/list")
    @ApiOperation(value = "能耗关键字查询",produces = "application/json",consumes = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "draw",value = "绘制次数",dataType = "Integer", paramType = "Integer", required = true),
            @ApiImplicitParam(name = "start",value = "查询起始位置",dataType = "Integer", paramType = "Integer", required = true),
            @ApiImplicitParam(name = "length",value = "查询条数",dataType = "Integer", paramType = "Integer", required = true),
            @ApiImplicitParam(name = "search",value = "产品名称关键字",dataType = "String", paramType = "String", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ReturnResult> productMonthEnergyQueryWordMethod(Integer draw,
                                                                           Integer start,
                                                                           Integer length,
                                                                           String search,
                                                                           @ApiIgnore HttpSession session){

        // 参数校验
        if(!EmptyUtils.isIntegerEmpty(start) && !EmptyUtils.isIntegerEmpty(length)){
            return ReturnOperator.createResultMsg(draw, 0, 0,
                    new ArrayList<>(),HttpStatus.OK);
        }

        // 取得当前登录的用户角色id
        Integer role_id = Integer.valueOf(String.valueOf(session.getAttribute("role_id")));
        // 取得当前登录的用户id
        Integer user_id = Integer.valueOf(String.valueOf(session.getAttribute("user_id")));


        // 包含产品月能耗和 项目名称 和 产品名称对象
        List<ProductMonthEnergyconsumptionVo> productMonthEnergyconsumptionVoList = null;
        Integer totalCount = 0;
        // 不是管理员的情况下
        if (role_id != 1) {
            // 关键字参数校验
            if(EmptyUtils.isStringEmpty(search)){
                totalCount = productMonthEnergyconsumptionService.queryAllByUserIdAndKeyWord(search,user_id).size();
                // 通过产品月能耗id和关联企业用户id查询
                productMonthEnergyconsumptionVoList = productMonthEnergyconsumptionService.queryAllByLimitAndUserIdAndKeyWord(search, start, length, user_id);

            } else {
                totalCount = productMonthEnergyconsumptionService.queryAllByUserId(user_id).size();
                // 通过产品月能耗id和关联企业用户id查询
                productMonthEnergyconsumptionVoList = productMonthEnergyconsumptionService.queryAllByLimitAndUserId(start, length, user_id);
            }

        }else {
            if(EmptyUtils.isStringEmpty(search)){
                totalCount = productMonthEnergyconsumptionService.queryAllByKeyWord(search).size();
                // 管理员情况下查询 产品月能耗id查询
                productMonthEnergyconsumptionVoList = productMonthEnergyconsumptionService.queryAllByLimitAndKeyWord(search,start, length);
            } else {
                totalCount = productMonthEnergyconsumptionService.queryAll().size();
                // 管理员情况下查询 产品月能耗id查询
                productMonthEnergyconsumptionVoList = productMonthEnergyconsumptionService.queryAllByLimit(start, length);
            }

        }

        // 查询结果参数校验
        if (!EmptyUtils.isProductMonthEnergyconsumptionListEmpty(productMonthEnergyconsumptionVoList)) {
            return ReturnOperator.createResultMsg(draw, 0, 0,
                    new ArrayList<>(),HttpStatus.OK);
        }

        // 返回数据
        return ReturnOperator.createResultMsg(draw, totalCount, totalCount,
                productMonthEnergyconsumptionVoList, HttpStatus.OK);

    }

    /**
     * 添加产品月能耗
     * @param productMonthEnergyconsumption    月能耗对象
     * @param errors        错误信息保存对象
     * @param session   Http回话对象内部存储当前登录的用户  user_id / user_name / role_id
     * @return
     */
    @PostMapping("/energy")
    @ApiOperation(value = "添加产品月能耗",produces = "application/json",consumes = "application/json")
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> productMonthEnergyAddMethod(@Valid @RequestBody ProductMonthEnergyconsumptionVo productMonthEnergyconsumption,
                                                     @ApiIgnore Errors errors,
                                                     @ApiIgnore HttpSession session){

        // 对象参数校验
        if (errors.hasErrors()) {
            List<ObjectError> oes = errors.getAllErrors();
            for (ObjectError oe : oes) {
                if (oe instanceof FieldError) {
                    FieldError fe = (FieldError) oe;
                    return ReturnOperator.createResultMsg("", fe.getDefaultMessage(), ServerStatus.ERROR,
                            new ArrayList(), emptyObject, HttpStatus.OK);
                } else {
                    return ReturnOperator.createResultMsg("", oe.getDefaultMessage(), ServerStatus.ERROR,
                            new ArrayList(), emptyObject, HttpStatus.OK);
                }
            }
        }

        // 取得当前登录的用户角色id
        Integer role_id = Integer.valueOf(String.valueOf(session.getAttribute("role_id")));
        // 取得当前登录的用户id
        Integer user_id = Integer.valueOf(String.valueOf(session.getAttribute("user_id")));


        // 不是管理员的情况下
        if (role_id != 1) {
            // 添加企业关联
            productMonthEnergyconsumption.setEnUserId(user_id);
        }

        // 项目id查询该项目下所有产品
        List<Product> productList = productService.queryByProjectBaseInfoId(productMonthEnergyconsumption.getProjectId());
        boolean exist = false;
        for(Product p : productList){
            // 判断是否有同名的产品
            if (p.getProductName().equals(productMonthEnergyconsumption.getProductName())) {
                // 将已有的产品id设置到 产品月能耗关联id上
                productMonthEnergyconsumption.setProductId(p.getId());
                exist = true;
            }
        }

        // 算出当月的每项标准煤填充到相应的对象字段中, 此处可作为扩展
//        ProductMonthEnergyconsumption productMonthEnergyconsumption_c = calculation(productMonthEnergyconsumption);

        // 如果存在则添加到
        ProductMonthEnergyconsumption productMonthEnergyconsumption_new = null;
        if (exist){
            // 将产品月能耗添加到数据库中
            productMonthEnergyconsumption_new = productMonthEnergyconsumptionService.insert(productMonthEnergyconsumption);
        }else {
            // 不存在 先创建产品
            Product product = new Product();
            // 不是管理员情况下
            if (role_id != 1) {
                // 设置成员属性
                product.setProjectBaseInfoId(productMonthEnergyconsumption.getProjectId());
                product.setProductName(productMonthEnergyconsumption.getProductName());
                product.setDeleted(0);
                // 不是管理员主要设置session中登录当前的用户id
                product.setEnUserId(user_id);

            }else {
                product.setProjectBaseInfoId(productMonthEnergyconsumption.getProjectId());
                product.setProductName(productMonthEnergyconsumption.getProductName());
                product.setDeleted(0);
                // 是管理员的情况下设置界面选择的用户id
                product.setEnUserId(productMonthEnergyconsumption.getEnUserId());
            }
            // 添加数据库中
            Product product_new = productService.insert(product);
            // 产品id设置到产品月能耗关联的id上
            productMonthEnergyconsumption.setProductId(product_new.getId());
            // 将产品月能耗添加到数据库中
            productMonthEnergyconsumption_new = productMonthEnergyconsumptionService.insert(productMonthEnergyconsumption);

        }

        // 添加后数据校验
        if (!EmptyUtils.isProductMonthEnergyconsumptionEmpty(productMonthEnergyconsumption_new)) {
            return ReturnOperator.createResultMsg("", ServerStatus.DATA_INSERT_ERR, ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        /**
         * 产品的年统计 是经过 产品的月记录进行计算得来
         */
        // 去系统当前时间的年部分
        Integer year = Integer.valueOf(new SimpleDateFormat("yyyy").format(new Date()));
        // 产品月能耗信息更变以后 进行 产品的年统计更新表
        if (!updateYearStatistic(productMonthEnergyconsumption_new.getProductId(), year)) {
            return ReturnOperator.createResultMsg(ServerStatus.MONTH_ADD_SUCCESS, "", ServerStatus.OK,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        /**
         * 项目的总能耗统计
         */
        // 用产品月能耗记录中的关联项目id查询 产品
        Product product = productService.queryById(productMonthEnergyconsumption_new.getProductId());
        // 用 产品信息中 关联项目的id查询项目
        ProjectBaseInfoVo projectBaseInfoVo = projectBaseInfoService.queryById(product.getProjectBaseInfoId());
        // 得到当前的年号
        Integer currentYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date()));
        // 统计项目的总能耗和能耗替代量+十三五入统能耗2020全年 + 十四五入统能耗2021全年
        if (!projectTotalEnergyconsumptionService.projectTotalEnergyConsumption(projectBaseInfoVo.getId(),currentYear-1,currentYear)) {
            return ReturnOperator.createResultMsg(ServerStatus.MONTH_YEAR_TOTAL_SUCCESS, "", ServerStatus.OK,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }


        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.MONTH_YEAR_TOTAL_RESULT_SUCCESS, "", ServerStatus.OK,
                new ArrayList(), productMonthEnergyconsumption_new, HttpStatus.OK);
    }




    /**
     * 修改产品月能耗
     * @param productMonthEnergyconsumption    产品月能耗对象
     * @param errors        错误信息保存对象
     * @param session   Http回话对象内部存储当前登录的用户  user_id / user_name / role_id
     * @return
     */
    @PutMapping("/energy")
    @ApiOperation(value = "修改产品月能耗",produces = "application/json",consumes = "application/json")
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> energyChangeByIdMethod(@Valid @RequestBody ProductMonthEnergyconsumptionVo productMonthEnergyconsumption,
                                                            @ApiIgnore Errors errors,
                                                            @ApiIgnore HttpSession session){
        // 对象参数校验
        if (errors.hasErrors()) {
            List<ObjectError> oes = errors.getAllErrors();
            for (ObjectError oe : oes) {
                if (oe instanceof FieldError) {
                    FieldError fe = (FieldError) oe;
                    return ReturnOperator.createResultMsg("", fe.getDefaultMessage(), ServerStatus.ERROR,
                            new ArrayList(), emptyObject, HttpStatus.OK);
                } else {
                    return ReturnOperator.createResultMsg("", oe.getDefaultMessage(), ServerStatus.ERROR,
                            new ArrayList(), emptyObject, HttpStatus.OK);
                }
            }
        }

        // 取得当前登录的用户角色id
        Integer role_id = Integer.valueOf(String.valueOf(session.getAttribute("role_id")));
        // 取得当前登录的用户id
        Integer user_id = Integer.valueOf(String.valueOf(session.getAttribute("user_id")));

        // 不是管理员的情况下
        if (role_id != 1) {
            // 添加企业关联
            productMonthEnergyconsumption.setEnUserId(user_id);
        }

        // 算出当月的每项标准煤填充到相应的对象字段中,此处可作为扩展
//        ProductMonthEnergyconsumption productMonthEnergyconsumption_c = calculation(productMonthEnergyconsumption);

        // 更新product
        Product product1 = productService.queryById(productMonthEnergyconsumption.getProductId());
        product1.setProductName(productMonthEnergyconsumption.getProductName());
        productService.update(product1);
        // 将计算后的产品月能耗更新到数据库中
        ProductMonthEnergyconsumption productMonthEnergyconsumption_new = productMonthEnergyconsumptionService.update(productMonthEnergyconsumption);
        // 添加后数据校验
        if (!EmptyUtils.isProductMonthEnergyconsumptionEmpty(productMonthEnergyconsumption_new)) {
            return ReturnOperator.createResultMsg("", ServerStatus.DATA_UPDATE_ERR, ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        /**
         * 产品的年统计 是经过 产品的月记录进行计算得来
         */
        // 去系统当前时间的年部分
        Integer year = Integer.valueOf(new SimpleDateFormat("yyyy").format(new Date()));
        // 产品月能耗信息更变以后 进行 年统计更新表
        if (!updateYearStatistic(productMonthEnergyconsumption_new.getProductId(), year)) {
            return ReturnOperator.createResultMsg(ServerStatus.MONTH_UPDATE_SUCCESS, "", ServerStatus.OK,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        /**
         * 项目的总能耗统计
         */
        // 用产品月能耗记录中的关联项目id查询 产品
        Product product = productService.queryById(productMonthEnergyconsumption_new.getProductId());
        // 用 产品信息中 关联项目的id查询项目
        ProjectBaseInfoVo projectBaseInfoVo = projectBaseInfoService.queryById(product.getProjectBaseInfoId());
        // 得到当前的年号
        Integer currentYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date()));
        // 统计项目的总能耗和能耗替代量+十三五入统能耗2020全年 + 十四五入统能耗2021全年
        if(!projectTotalEnergyconsumptionService.projectTotalEnergyConsumption(projectBaseInfoVo.getId(),currentYear-1,currentYear)){
            return ReturnOperator.createResultMsg(ServerStatus.MONTH_YEAR_UPDATE_TOTAL_SUCCESS, "", ServerStatus.OK,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.MONTH_YEAR_UPDATE_TOTAL_RESULT_SUCCESS, "", ServerStatus.OK,
                new ArrayList(), emptyObject, HttpStatus.OK);
    }

    /**
     * id删除产品月能耗
     * @param id    产品月能耗id
     * @param session   Http回话对象内部存储当前登录的用户  user_id / user_name / role_id
     * @return
     */
    @DeleteMapping("/energy/{id}")
    @ApiOperation(value = "id删除产品月能耗",produces = "application/json",consumes = "application/json")
    @ApiImplicitParam(name = "id",value = "产品月能耗id",required = true, dataType = "Long", paramType = "Long", dataTypeClass = Long.class)
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> energyDeleteByIdMethod(@PathVariable("id") Long id,@ApiIgnore HttpSession session){

        // id参数校验
        if (!EmptyUtils.isLongEmpty(id)) {
            return ReturnOperator.createResultMsg("", ServerStatus.ID_NOT_NULL, ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        // 取得当前登录的用户角色id
        Integer role_id = Integer.valueOf(String.valueOf(session.getAttribute("role_id")));
        // 取得当前登录的用户id
        Integer user_id = Integer.valueOf(String.valueOf(session.getAttribute("user_id")));


        // 不是管理员的情况下
        if (role_id != 1) {

            // 查询关联企业用户id和 产品月能耗查询
            ProductMonthEnergyconsumptionVo productMonthEnergyconsumptionVo = productMonthEnergyconsumptionService.queryProductMonthEnergyByIdAndUserId(id, user_id);

            if (!EmptyUtils.isProductMonthEnergyconsumptionEmpty(productMonthEnergyconsumptionVo)) {
                return ReturnOperator.createResultMsg("", ServerStatus.QUERY_MESSAGE_ERR, ServerStatus.ERROR,
                        new ArrayList(), new Boolean(false), HttpStatus.OK);
            }
            productService.deleteById(productMonthEnergyconsumptionVo.getProductId());

            // 因为管理员就是无限制,如果是企业用户显示的也是企业用户自己的数据所以id删除不需要关联企业用户id进行删除,直接删除即可
            if (!productMonthEnergyconsumptionService.deleteById(id)) {
                return ReturnOperator.createResultMsg("", ServerStatus.DATA_DELETE_ERR, ServerStatus.ERROR,
                        new ArrayList(), new Boolean(false), HttpStatus.OK);
            }

            // 查询出所有跟product_id关联的能耗记录
            List<ProductMonthEnergyconsumptionVo> productMonthEnergyconsumptionVo1 = productMonthEnergyconsumptionService.queryProductMonthEnergyAndProductById(productMonthEnergyconsumptionVo.getProductId());
            // 如果没有记录了将产品也删除
            if(productMonthEnergyconsumptionVo1 == null || productMonthEnergyconsumptionVo1.size() == 0){
                // 删除产品
                productService.deleteById(productMonthEnergyconsumptionVo.getProductId());

                // 根据产品id查询年能耗信息
                ProductYearEnergyconsumption productYearEnergyconsumption = productYearEnergyconsumptionService.queryByProductId(productMonthEnergyconsumptionVo.getProductId());
                // 将年能耗删除
                productYearEnergyconsumptionService.deleteById(productYearEnergyconsumption.getId());
            }

            // 去系统当前时间的年部分
            Integer year = Integer.valueOf(new SimpleDateFormat("yyyy").format(new Date()));
            // 产品月能耗信息更变以后 进行 年统计更新表 有user_id的情况下
            if (!updateYearStatistic(productMonthEnergyconsumptionVo.getProductId(), year,user_id)) {
                return ReturnOperator.createResultMsg("", ServerStatus.MONTH_DELETE_SUCCESS, ServerStatus.ERROR,
                        new ArrayList(), emptyObject, HttpStatus.OK);
            }
        } else {

            // 查询关联企业用户id和 产品月能耗查询
            ProductMonthEnergyconsumptionVo productMonthEnergyconsumptionVo = productMonthEnergyconsumptionService.queryProductMonthEnergyById(id);

            if (!EmptyUtils.isProductMonthEnergyconsumptionEmpty(productMonthEnergyconsumptionVo)) {
                return ReturnOperator.createResultMsg("", ServerStatus.QUERY_MESSAGE_ERR, ServerStatus.ERROR,
                        new ArrayList(), new Boolean(false), HttpStatus.OK);
            }

            // 因为管理员就是无限制,如果是企业用户显示的也是企业用户自己的数据所以id删除不需要关联企业用户id进行删除,直接删除即可
            if (!productMonthEnergyconsumptionService.deleteById(id)) {
                return ReturnOperator.createResultMsg("", ServerStatus.DATA_DELETE_ERR, ServerStatus.ERROR,
                        new ArrayList(), new Boolean(false), HttpStatus.OK);
            }

            // 查询出所有跟product_id关联的能耗记录
            List<ProductMonthEnergyconsumptionVo> productMonthEnergyconsumptionVo1 = productMonthEnergyconsumptionService.queryProductMonthEnergyAndProductById(productMonthEnergyconsumptionVo.getProductId());
            // 如果没有记录了将产品也删除
            if(productMonthEnergyconsumptionVo1 == null || productMonthEnergyconsumptionVo1.size() == 0){
                // 删除产品
                productService.deleteById(productMonthEnergyconsumptionVo.getProductId());
                // 根据产品id查询年能耗信息
                ProductYearEnergyconsumption productYearEnergyconsumption = productYearEnergyconsumptionService.queryByProductId(productMonthEnergyconsumptionVo.getProductId());
                // 将年能耗删除
                productYearEnergyconsumptionService.deleteById(productYearEnergyconsumption.getId());
            }

            // 去系统当前时间的年部分
            Integer year = Integer.valueOf(new SimpleDateFormat("yyyy").format(new Date()));
            // 产品月能耗信息更变以后 进行 年统计更新表
            if (!updateYearStatistic(productMonthEnergyconsumptionVo.getProductId(), year)) {
                return ReturnOperator.createResultMsg("", ServerStatus.MONTH_DELETE_SUCCESS, ServerStatus.ERROR,
                        new ArrayList(), emptyObject, HttpStatus.OK);
            }
        }

        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.DATA_DELETE_SUCCESS, "", ServerStatus.OK,
                new ArrayList(), new Boolean(true), HttpStatus.OK);
    }


    /**
     * id数组批量删除产品月能耗 没有做对产品的年统计更新因为拿不到 产品的id关联id
     * @param ids   产品月能耗id数组
     * @param session   Http回话对象内部存储当前登录的用户  user_id / user_name / role_id
     * @return
     */
    @DeleteMapping("/energy")
    @ApiOperation(value = "能耗批量删除",produces = "application/json",consumes = "application/json")
    @ApiImplicitParam(name = "ids",value = "产品月能耗id数组",dataType = "Long", dataTypeClass = Long.class, paramType = "Long[]", required = true)
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> energyDeleteListByIDMethod(Long[] ids,@ApiIgnore HttpSession session){

        // id参数校验
        if (!EmptyUtils.isIdsEmpty(ids)) {
            return ReturnOperator.createResultMsg("", ServerStatus.ID_NOT_NULL, ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        // 循环删除
        for (Long id : ids) {
            productMonthEnergyconsumptionService.deleteById(id);
        }

        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.DATA_DELETE_SUCCESS, "", ServerStatus.OK,
                new ArrayList(), new Boolean(true), HttpStatus.OK);
    }



    /**
     * 算出当月的每项标准煤填充到相应的对象字段中
     * @param productMonthEnergyconsumption
     * @return
     */
    private ProductMonthEnergyconsumption calculation(ProductMonthEnergyconsumption productMonthEnergyconsumption) {

        // 每月电力折合成标准煤当量值（tce）
        productMonthEnergyconsumption.setElectricityConvCoal(
                CalculatedValue.electricityConvStandardCoal(productMonthEnergyconsumption.getProductMonthElectricity())
        );

        // 每月煤炭折合成标准煤（tce）
        productMonthEnergyconsumption.setCoalConvCoal(
                CalculatedValue.coalConvStandardCoal(productMonthEnergyconsumption.getProductMonthCoal())
        );
        // 每月燃料油折合成标准煤（tce）
        productMonthEnergyconsumption.setFueloilConvCoal(
                CalculatedValue.fueloilConvStandardCoal(productMonthEnergyconsumption.getProductMonthFueloil())
        );
        //  每月天然气折合成标准煤（tce）
        productMonthEnergyconsumption.setNaturalgasConvCoal(
                CalculatedValue.naturalgasConvStandardCoal(productMonthEnergyconsumption.getProductMonthNaturalgas())
        );
        //  每月水折合成标准煤（tce）
        productMonthEnergyconsumption.setWaterConvCoal(
                CalculatedValue.waterConvStandardCoal(productMonthEnergyconsumption.getProductMonthWater())
        );

        return productMonthEnergyconsumption;
    }


    /**
     * 添加或更新年统计记录
     * @param productId 产品id
     * @return
     */
    private boolean updateYearStatistic(Long productId, Integer year) {

        // 数据库月能耗记录更变之后进行年运算统计(只是查询运算没有添加到数据库)
        ProductYearEnergyconsumptionVo productYearEnergyconsumptionVo = productYearEnergyconsumptionService.productYearStatisticEnergyByProductId(productId, year);

        if (productYearEnergyconsumptionVo == null) {
            return false;
        }
        // 产品id查询 产品年的能耗 是否存在 存在则更新 不存在则 添加
        ProductYearEnergyconsumption productYearEnergyconsumption = productYearEnergyconsumptionService.queryByProductId(productId);
        if (!EmptyUtils.isProductYearEnergyconsumptionEmpty(productYearEnergyconsumption)) {
            // 设置当前年
            productYearEnergyconsumptionVo.setYear(year);
            // 将包含企业名,项目名,产品名的 对象转为 符合添加数据库的对象 进行添加
            productYearEnergyconsumptionService.insert((ProductYearEnergyconsumption)productYearEnergyconsumptionVo);
        } else {
            // 设置当前年
            productYearEnergyconsumption.setYear(year);
            // 设置产品年产量
            productYearEnergyconsumption.setYearYield(productYearEnergyconsumptionVo.getYearYield());
            // 设置产品年销售量
            productYearEnergyconsumption.setYearSalesIncome(productYearEnergyconsumptionVo.getYearSalesIncome());

            // 设置产品年电力能耗量和标准煤
            productYearEnergyconsumption.setYearElectricityConsume(productYearEnergyconsumptionVo.getYearElectricityConsume());
            productYearEnergyconsumption.setElectricityConvCoal(productYearEnergyconsumptionVo.getElectricityConvCoal());
            // 设置产品年煤炭能耗量和标准煤
            productYearEnergyconsumption.setYearCoalConsume(productYearEnergyconsumptionVo.getYearCoalConsume());
            productYearEnergyconsumption.setCoalConvStandardcoal(productYearEnergyconsumptionVo.getCoalConvStandardcoal());
            // 设置产品年天然气能耗量和标准煤
            productYearEnergyconsumption.setYearNaturalgasConsume(productYearEnergyconsumptionVo.getYearNaturalgasConsume());
            productYearEnergyconsumption.setNaturalgasConvStandardcoal(productYearEnergyconsumptionVo.getNaturalgasConvStandardcoal());
            // 设置产品年燃料油能耗量和标准煤
            productYearEnergyconsumption.setYearFueloilConsume(productYearEnergyconsumptionVo.getYearFueloilConsume());
            productYearEnergyconsumption.setFueloilConvStandardcoal(productYearEnergyconsumptionVo.getFueloilConvStandardcoal());
            // 设置产品年水能耗量和标准煤
            productYearEnergyconsumption.setYearWaterConsume(productYearEnergyconsumptionVo.getYearWaterConsume());
            productYearEnergyconsumption.setWaterConvStandardcoal(productYearEnergyconsumptionVo.getWaterConvStandardcoal());
            // 设置产品年能耗合计
            productYearEnergyconsumption.setEnTotal(productYearEnergyconsumptionVo.getEnTotal());
            // 设置产品年 单位产品能耗
            productYearEnergyconsumption.setProductEn(productYearEnergyconsumptionVo.getProductEn());
            // 设置产品年 能耗强度
            productYearEnergyconsumption.setEnStrength(productYearEnergyconsumptionVo.getEnStrength());
            // 更新数据库
            productYearEnergyconsumptionService.update(productYearEnergyconsumption);
        }

        return true;
    }

    /**
     * 添加或更新年统计记录 有userid的情况下
     * @param productId 产品id
     * @return
     */
    private boolean updateYearStatistic(Long productId, Integer year, Integer userId) {

        // 数据库月能耗记录更变之后进行年运算统计(只是查询运算没有添加到数据库)
        ProductYearEnergyconsumptionVo productYearEnergyconsumptionVo = productYearEnergyconsumptionService.productYearStatisticEnergyByproductIdAndUserId(productId, year,userId);

        if(productYearEnergyconsumptionVo == null) {
            return false;
        }

        // 产品id查询 产品年的能耗 是否存在 存在则更新 不存在则 添加
        ProductYearEnergyconsumption productYearEnergyconsumption = productYearEnergyconsumptionService.queryByProductId(productId);
        if (!EmptyUtils.isProductYearEnergyconsumptionEmpty(productYearEnergyconsumption)) {
            // 将包含企业名,项目名,产品名的 对象转为 符合添加数据库的对象 进行添加
            productYearEnergyconsumptionService.insert((ProductYearEnergyconsumption)productYearEnergyconsumptionVo);
        } else {
            // 设置产品年产量
            productYearEnergyconsumption.setYearYield(productYearEnergyconsumptionVo.getYearYield());
            // 设置产品年销售量
            productYearEnergyconsumption.setYearSalesIncome(productYearEnergyconsumptionVo.getYearSalesIncome());

            // 设置产品年电力能耗量和标准煤
            productYearEnergyconsumption.setYearElectricityConsume(productYearEnergyconsumptionVo.getYearElectricityConsume());
            productYearEnergyconsumption.setElectricityConvCoal(productYearEnergyconsumptionVo.getElectricityConvCoal());
            // 设置产品年煤炭能耗量和标准煤
            productYearEnergyconsumption.setYearCoalConsume(productYearEnergyconsumptionVo.getYearCoalConsume());
            productYearEnergyconsumption.setCoalConvStandardcoal(productYearEnergyconsumptionVo.getCoalConvStandardcoal());
            // 设置产品年天然气能耗量和标准煤
            productYearEnergyconsumption.setYearNaturalgasConsume(productYearEnergyconsumptionVo.getYearNaturalgasConsume());
            productYearEnergyconsumption.setNaturalgasConvStandardcoal(productYearEnergyconsumptionVo.getNaturalgasConvStandardcoal());
            // 设置产品年燃料油能耗量和标准煤
            productYearEnergyconsumption.setYearFueloilConsume(productYearEnergyconsumptionVo.getYearFueloilConsume());
            productYearEnergyconsumption.setFueloilConvStandardcoal(productYearEnergyconsumptionVo.getFueloilConvStandardcoal());
            // 设置产品年水能耗量和标准煤
            productYearEnergyconsumption.setYearWaterConsume(productYearEnergyconsumptionVo.getYearWaterConsume());
            productYearEnergyconsumption.setWaterConvStandardcoal(productYearEnergyconsumptionVo.getWaterConvStandardcoal());
            // 设置产品年能耗合计
            productYearEnergyconsumption.setEnTotal(productYearEnergyconsumptionVo.getEnTotal());
            // 设置产品年 单位产品能耗
            productYearEnergyconsumption.setProductEn(productYearEnergyconsumptionVo.getProductEn());
            // 设置产品年 能耗强度
            productYearEnergyconsumption.setEnStrength(productYearEnergyconsumptionVo.getEnStrength());
            // 更新数据库
            productYearEnergyconsumptionService.update(productYearEnergyconsumption);
        }

        return true;
    }
}
